<?php

namespace App\Admin\Controllers\Api;

use App\Admin\Controllers\BaseAdminController;
use App\Admin\Renderable\MicroAppTable;
use App\Models\Open\ApiInfo;
use App\Models\Open\MicroApp;
use App\Models\Open\Platform;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;

class ApiInfoController extends BaseAdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(ApiInfo::with(['adminUser', 'platform', 'appType', 'microApps']), function (Grid $grid) {
            $grid->enableDialogCreate();
            $grid->disableEditButton();
            $grid->showQuickEditButton('编辑');

            $grid->column('platform.name', admin_trans_field('platform_name'));
            $grid->column('appType.name', admin_trans_field('app_type_name'));
            $grid->column('name');
            $grid->column('aliasname');
            $grid->column('path');
            $grid->column('description');
            $grid->microApps()->pluck('name')->label();
            $grid->column('adminUser.username', admin_trans_field('admin_username'));
            $grid->column('updated_at')->sortable();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, ApiInfo::with(['adminUser']), function (Show $show) {
            $show->field('name');
            $show->field('path');
            $show->field('description');
            $show->field('admin_user_id');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(ApiInfo::with(['adminUser', 'microApps']), function (Form $form) {
            $adminId = Admin::user()->getKey();
            $form->select('platform_id', admin_trans_field('platform_name'))
                ->options(function () {
                    return Platform::all()->pluck('name', 'id');
                })->load('app_type_id', 'app-type-search');
            $form->select('app_type_id', admin_trans_field('app_type_name'));
            $form->text('name');
            $form->text('aliasname');
            $form->text('path');
            $form->textarea('description');
            $form->hidden('admin_user_id')->value($adminId);
            $form->multipleSelectTable('microApps')
                ->title('Micro Apps')
                ->max(10)
                ->from(MicroAppTable::make())
                ->model(MicroApp::class, 'id', 'name')
                ->customFormat(function ($v) {
                    if (! $v) {
                        return [];
                    }
                    return array_column($v, 'id');
                });
        });
    }
}
